<template>
  <el-dialog
    :visible="visible"
    :title="title"
    class="add-role-dialog"
    align-center
    @opened="handleDialogOpen"
    @close="closeDialog"
  >
    <div class="content">
      <div class="left">
        <el-form
          :model="roleForm"
          :rules="roleRules"
          ref="roleFormRef"
          label-width="80px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="roleForm.roleName" />
          </el-form-item>
          <el-form-item label="角色描述" prop="remark">
            <el-input v-model="roleForm.remark" type="textarea" />
          </el-form-item>
          <el-form-item label="角色等级" class="role-level" prop="remark">
            <el-radio-group
              v-model="roleForm.roleLevel"
              :disabled="!!roleForm.pkid"
            >
              <el-radio :label="'3'">社区级</el-radio>
              <el-radio :label="'1'">街道级</el-radio>
              <el-radio :label="'2'">区县级</el-radio>
              <el-radio :label="'5'">片区级</el-radio>
              <el-radio :label="'0'">市级</el-radio>
              <el-radio :label="'4'">超级管理员</el-radio>
              <el-radio :label="'6'">数据调查</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="状态" prop="remark">
            <el-radio-group v-model="roleForm.status">
              <el-radio :label="'1'">启用</el-radio>
              <el-radio :label="'0'">禁用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <div class="right">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="菜单目录" name="menu">
            <div class="right-content">
              <el-input
                v-model="menuSearch"
                placeholder="请输入"
                prefix-icon="Search"
              />
              <el-tree
                :data="menuTree"
                :props="defaultProps"
                :check-strictly="true"
                show-checkbox
                node-key="pkid"
                default-expand-all
                :default-checked-keys="defaultCheckedKeys"
                @check="onCheck"
                :expand-on-click-node="false"
                ref="treeRef"
                :filter-node-method="filterNode"
              >
                <template #default="{ node }">
                  <span class="custom-tree-node">
                    <span>{{ node.label }}</span>
                  </span>
                </template>
              </el-tree>
            </div>
          </el-tab-pane>
          <!-- <el-tab-pane label="数据目录" name="data">
            <div class="right-content">
              <el-input
                v-model="dataSearch"
                placeholder="请输入"
                prefix-icon="Search"
              />
              <el-tree
                :data="dataTree"
                :props="defaultProps"
                :check-strictly="true"
                show-checkbox
                node-key="pkid"
                default-expand-all
                :default-checked-keys="dataDefaultCheckedKeys"
                @check="onDataChech"
                :expand-on-click-node="false"
                ref="dataTreeRef"
                :filter-node-method="filterNode"
              >
                <template #default="{ node }">
                  <span class="custom-tree-node">
                    <span>{{ node.label }}</span>
                  </span>
                </template>
              </el-tree>
            </div>
          </el-tab-pane> -->
        </el-tabs>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="onSubmit"> 确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { getCurrentInstance, onMounted, reactive, ref, watch } from 'vue'
import {
  addRole,
  editRole,
  bindRolePermission,
  queryRolePermission,
} from '@/api/back-management/role'
import { Message as ElMessage } from 'element-ui'
// import { Search } from '@element-plus/icons-vue'
import { queryMenuList } from '@/api/back-management/menu'
import type { MenuTree } from '@/api/back-management/menu/interface'
import cache from '@/utils/cache'
// import { useCurrentUserStore } from '@/stores/current-user'

interface CatalogItem {
  id: string
  name: string
  type: CatalogItemType
  checked?: boolean
  parent?: string
  icon?: string
  children?: CatalogItem[]
}

interface Tree {
  [key: string]: any
}

type CatalogItemType = 'catalog' | 'service'

const menuListDisabled = (data: MenuTree) => {
  return data.status === '0'
}

const activeTab = ref('menu')

const defaultProps = {
  children: 'children',
  label: 'catalogName',
  disabled: menuListDisabled as any,
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
  roleInfo: {
    type: Object,
    default: () => {},
  },
  roleRoleDict: {
    type: Array,
    default: () => [],
  },
})

// const currentUserStore = useCurrentUserStore()
const vm = getCurrentInstance()
const store = vm?.proxy?.$store

const currentUserStore = store?.state?.user

const getMenuTreeList = (type = 4, tree: any[]) => {
  queryMenuList({
    // type: type,
  })
    .then((res) => {
      if (res.success) {
        tree.value = res.data[0].children
      } else {
        ElMessage.error(res.message)
      }
    })
    .catch((e) => {
      ElMessage.error(e)
    })
}

const title = ref('新增角色')

const menuSearch = ref('')
const dataSearch = ref('')

const treeRef = ref()
const dataTreeRef = ref()

const menuTree = ref<MenuTree[]>([])
const dataTree = ref([])

watch(
  () => menuSearch.value,
  (val) => {
    treeRef.value!.filter(val)
  }
)

watch(
  () => dataSearch.value,
  (val) => {
    dataTreeRef.value!.filter(val)
  }
)

const filterNode = (value: string, data: Tree) => {
  if (!value) return true
  return data.catalogName.includes(value)
}

const emit = defineEmits(['closeDialog', 'updateRole'])

const closeDialog = () => {
  emit('closeDialog')
}

const roleForm = reactive({
  roleName: '',
  remark: '',
  roleLevel: '3',
  status: '1',
  pkid: '',
})

const roleFormRef = ref()

const roleRules = reactive({
  roleName: [
    {
      required: true,
      message: '角色名称不能为空',
      trigger: 'blur',
    },
    {
      pattern: /^[^\s*$]/,
      message: '不能只输入空格或以空格开始',
    },
  ],
})

const checkedKeys = ref([])

const dataCheckedKeys = ref([])

const defaultCheckedKeys = ref([''])

const dataDefaultCheckedKeys = ref([''])

const onSubmit = async () => {
  const verifyResult = await roleFormRef.value?.validate()
  if (verifyResult) {
    const { id, success } = await addOrUpdateRole()
    if (success) {
      bindPermission(id)
    }
  }
}

// 新增或编辑角色基本信息
const addOrUpdateRole = async () => {
  const params = {
    pkid: roleForm.pkid,
    roleName: roleForm.roleName,
    remark: roleForm.remark,
    roleLevel: roleForm.roleLevel,
  }
  const result = {
    id: '',
    success: false,
  }
  if (roleForm.pkid) {
    await editRole(roleForm.pkid, params)
      .then((res) => {
        if (res.success) {
          result.success = true
          if (!checkedKeys.value.length) {
            emit('updateRole')
            ElMessage.success('修改角色成功')
          }
        }
      })
      .catch((e) => {
        ElMessage.error(e)
      })
  } else {
    await addRole(params)
      .then((res) => {
        if (res.success) {
          result.success = true
          result.id = res.data
          if (!checkedKeys.value.length) {
            emit('updateRole')
            ElMessage.success('添加角色成功')
          }
        }
      })
      .catch((e) => {
        ElMessage.error(e)
      })
  }
  return result
}

const bindMenuPermission = (roleId: string) => {
  const id = roleId ? roleId : roleForm.pkid
  const checkedKeys = treeRef.value!.getCheckedKeys()
  const halfCheckedKeys = treeRef.value!.getHalfCheckedKeys()
  const idList = Array.from(new Set(halfCheckedKeys.concat(checkedKeys)))

  // const params = idList.map((item) => {
  //   return {
  //     roleId: id,
  //     resourceId: item,
  //     resourceType: 4,
  //   }
  // })
  const params = {
    roleId: id,
    resourceIds: idList
  }
  return bindRolePermission(params, id)
}

// const bindDataPermission = (roleId: string) => {
//   const id = roleId ? roleId : roleForm.pkid
//   const checkedKeys = dataTreeRef.value!.getCheckedKeys()
//   const halfCheckedKeys = dataTreeRef.value!.getHalfCheckedKeys()
//   const idList = Array.from(new Set(halfCheckedKeys.concat(checkedKeys)))
  
//   // const params = idList.map((item) => {
//   //   return {
//   //     roleId: id,
//   //     resourceId: item,
//   //     resourceType: 1,
//   //   }
//   // })

//   const params = {
//     roleId: id,
//     resourceIds: idList
//   }
//   return bindRolePermission(params, id, 1)
// }

// 给角色绑定权限
const bindPermission = (roleId: string) => {
  Promise.all([bindMenuPermission(roleId)])
    .then((res) => {
      if (res[0].success) {
        emit('updateRole')
        let msg = ''
        roleForm.pkid ? (msg = '修改') : (msg = '添加')
        ElMessage.success(`${msg}角色成功`)
        if (
          roleForm.pkid &&
          cache.getItem('user_role_level') === roleForm.roleLevel
        ) {
          currentUserStore.logout()
        }
      }
    })
    .catch(() => {
      return false
    })
}

const handleDialogOpen = () => {
  if (props.roleInfo) {
    const { pkid, roleName, remark, roleLevel } = props.roleInfo
    roleForm.pkid = pkid
    roleForm.roleName = roleName
    roleForm.remark = remark
    if (roleLevel !== undefined) {
      roleForm.roleLevel = roleLevel?.toString()
    }
    activeTab.value = 'menu'
    if (pkid) {
      title.value = '编辑角色'
      queryRolePermission(pkid).then((res) => {
        const data = res.data
        treeRef.value?.setCheckedKeys([])
        defaultCheckedKeys.value = []
        if (data) {
          getTreeCheckId(data.menuList[0].children, defaultCheckedKeys)
          checkedKeys.value = JSON.parse(
            JSON.stringify(defaultCheckedKeys.value)
          )
        }
      })
      // queryRolePermission(pkid, 1).then((res) => {
      //   const data = res.data
      //   dataTreeRef.value?.setCheckedKeys([])
      //   dataDefaultCheckedKeys.value = []
      //   if (data.length) {
      //     // console.log(data)
      //     getTreeCheckId(data, dataDefaultCheckedKeys)
      //     dataCheckedKeys.value = JSON.parse(
      //       JSON.stringify(dataDefaultCheckedKeys.value)
      //     )
      //   }
      // })
    } else {
      treeRef.value!.setCheckedKeys([], false)
      dataTreeRef.value!.setCheckedKeys([], false)
      defaultCheckedKeys.value = []
      dataDefaultCheckedKeys.value = []
      checkedKeys.value = []
      dataCheckedKeys.value = []
      title.value = '新增角色'
    }
  }
}

const onCheck = (data: CatalogItem, state: any) => {
  checkedKeys.value = state.checkedKeys.concat(state.halfCheckedKeys) as []
}

const onDataChech = (data: CatalogItem, state: any) => {
  dataCheckedKeys.value = state.checkedKeys.concat(state.halfCheckedKeys) as []
}

const getTreeCheckId = (data: MenuTree[], keys: any[]) => {
  // console.log(data);
  data.map((item) => {
    if (item.children && item.children.length) {
      if (item.hasPri) {
        keys.value.push(item.pkid as string)
      }
      getTreeCheckId(item.children, keys)
    } else {
      // console.log(item);
      if (item.hasPri) {
        keys.value.push(item.pkid as string)
      }
    }
  })
}

onMounted(() => {
  getMenuTreeList(4, menuTree)
  // getMenuTreeList(1, dataTree)
})
</script>

<style lang="scss">
.add-role-dialog {
  //width: 862px;
  //height: 703px;
  //background: #ffffff;
  border-radius: 4px;

  .el-dialog__footer {
    padding-top: 30px !important;
    border-top: 1px solid #e5e5e5;
  }

  .el-dialog__header {
    border-bottom: 1px solid #e5e5e5;

    .el-dialog__title {
      width: 64px;
      height: 16px;
      font-size: 16px;
      font-weight: bold;
      color: #27475f;
    }
  }

  .el-dialog__body {
    height: 80.22%;
    padding: 0;
    //border-bottom: 1px solid #e5e5e5;
  }

  .content {
    height: 100%;
    display: flex;

    .left {
      width: 47%;
      padding-top: 30px;
      padding-left: 20px;
      padding-bottom: 30px;
      padding-right: 36px;
      border-right: 1px solid #e5e5e5;

      .el-form {
        .el-form-item {
          min-height: 42px;
          margin-bottom: 21px;
          align-items: center;
        }

        .role-level {
          align-items: flex-start;
        }

        .el-cascader {
          width: 100%;
        }

        .el-select {
          width: 100%;
        }
      }
    }

    .right {
      width: 52%;

      .el-tabs__nav {
        margin-left: 20px;
      }

      .right-title {
        height: 40px;
        line-height: 40px;
        padding-left: 26px;
        border-bottom: 1px solid #e5e5e5;
      }

      .right-content {
        padding: 0 36px 0 20px;
        height: calc(100% - 40px);

        .el-input {
          margin-top: 12px;
          margin-bottom: 12px;
        }

        .el-tree {
          height: calc(100% - 32px - 24px);
          overflow-y: auto;
        }
      }
    }
  }

  .dialog-footer {
    width: 100%;
    height: 100%;
    text-align: center;
  }
}
</style>
